package com.example.algorithm.greedy;

import java.util.Arrays;
import java.util.stream.IntStream;

/**
 * @author : zhy
 * @since : 2022/8/30
 * 1005. K次取反后最大化的数组和
 */
public class KNumSumAbs {

    public int largestSumAfterKNegations(int[] nums, int k) {
        int len=nums.length;
        nums=IntStream.of(nums).boxed().sorted((o1,o2)->Math.abs(o2)-Math.abs(o1)).mapToInt(Integer::intValue).toArray();
        for(int i=0;i<len;i++)
        {
            if(nums[i]<0&&k>0)
            {
                nums[i]=-nums[i];
                k--;
            }
        }
        if(k%2==1)
        {
            nums[len-1]=-nums[len-1];
        }
        return Arrays.stream(nums).sum();
    }

    public static void main(String[] args) {
        KNumSumAbs kNumSumAbs = new KNumSumAbs();
        int []can={3,-1,0,2};
        System.out.println(kNumSumAbs.largestSumAfterKNegations(can, 3));
    }
}
